package com.pleague.common.utils;
/**
 * Created by zhanglin on 2017/4/25.
 */
public class MoneyUtils {
    /**
     * 将元为单位的数额转换为分
     * @param amount
     * @return
     */
    public static String yuanToFee(String amount){
        String currency =  amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if(index == -1){
            amLong = Long.valueOf(currency+"00");
        }else if(length - index >= 3){
            amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
        }else if(length - index == 2){
            amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
        }else{
            amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
        }
        return amLong.toString();
    }

    /**
     * 将分为单位的数额转换为元
     * @param amount
     * @return
     */
    public static String feeToYuan(Long amount){
        try {
            if(!amount.toString().matches("\\-?[0-9]+"));
        }catch (Exception e) {
            throw new RuntimeException("分转成元出错!",e);
        }
        int flag = 0;
        String amString = amount.toString();
        if(amString.charAt(0)=='-'){
            flag = 1;
            amString = amString.substring(1);
        }
        StringBuffer result = new StringBuffer();
        if(amString.length()==1){
            result.append("0.0").append(amString);
        }else if(amString.length() == 2){
            result.append("0.").append(amString);
        }else{
            String intString = amString.substring(0,amString.length()-2);
            for(int i=1; i<=intString.length();i++){
                if( (i-1)%3 == 0 && i !=1){
                    result.append(",");
                }
                result.append(intString.substring(intString.length()-i,intString.length()-i+1));
            }
            result.reverse().append(".").append(amString.substring(amString.length()-2));
        }
        if(flag == 1){
            return "-"+result.toString();
        }else{
            return result.toString();
        }
    }

    /**
     * 将分为单位的数额转换为元
     * @param amount
     * @return
     */
    public static String feeToYuan(String amount){
        return feeToYuan(Long.valueOf(amount));
    }

    public static void main(String[] args){

        System.out.println(yuanToFee("100"));

        System.out.println(feeToYuan(Long.valueOf(10001)));

    }

}
